export const isAdmin = menus => {
  if (!menus) {
    return false;
  }
  return menus.filter(x => x.showed).length > 0;
};

//openParam: {urlParam:{id,url},newPageData:any}
export const openWindow = openParam => {
  // console.log('openWindow', openParam)
  if (openParam.urlParam.url) {
    if (typeof g.ipcRenderer !== "undefined") {
      if (openParam.urlParam.url.indexOf("electron") > -1) {
        g.ipcRenderer.send("create_window", JSON.stringify(openParam));
      } else {
        g.ipcRenderer.send("open_url", openParam.urlParam.url);
      }
    } else {
      jsOpenNewWindow(openParam.urlParam.url);
    }
  } else {
    console.error("no param url", openParam.urlParam);
  }
};
// formatDate, getDateByTimeUnit
// 添加以下函数
export function formatDate(fdate, format = "YYYY-MM-dd") {
  if (!fdate) {
    return "";
  }

  // 处理日期字符串的兼容性问题
  if (typeof fdate === "string") {
    // 替换连字符为斜杠以提高跨浏览器兼容性
    fdate = fdate.replace(/-/g, "/");
  }

  // 创建日期对象并验证
  const dateObj = new Date(fdate);
  if (isNaN(dateObj.getTime())) {
    console.error("Invalid date:", fdate);
    return "";
  }

  var date = {
    "Y+": dateObj.getFullYear(),
    "M+": dateObj.getMonth() + 1,
    "d+": dateObj.getDate(),
    "h+": dateObj.getHours(),
    "m+": dateObj.getMinutes(),
    "s+": dateObj.getSeconds(),
    "q+": Math.floor((dateObj.getMonth() + 3) / 3),
    "S+": dateObj.getMilliseconds(),
    "w+": ["日", "一", "二", "三", "四", "五", "六"][dateObj.getDay()]
  };

  if (/(y+)/i.test(format)) {
    format = format.replace(
      RegExp.$1,
      (dateObj.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }

  for (var k in date) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1
          ? date[k]
          : ("00" + date[k]).substr(("" + date[k]).length)
      );
    }
  }
  return format;
}

export function now(dt_dormat = "yyyy-MM-dd hh:mm:ss") {
  return formatDate(new Date(), dt_dormat);
}

//添加一个函数，返回离现在最新的目录最近一的一个整10分钟的点，比如现在 2024-10-23 15:21：23，应该返回2024-10-23 15:30:00
export function nowMNAfter(dt_format = "yyyy-MM-dd hh:mm:ss", m = 10, n = 0) {
  const nowDate = new Date();
  nowDate.setMinutes(Math.ceil(nowDate.getMinutes() / m) * m + n);
  nowDate.setSeconds(0);
  nowDate.setMilliseconds(0);
  return formatDate(nowDate, dt_format);
}

export function nDate(n = 0, format = "YYYY-MM-dd") {
  return formatDate(addDays(new Date(), n), format);
}

export function addDays(date, n) {
  var result = new Date(date);
  result.setDate(result.getDate() + n);
  return result;
}

export function formatDuration(duration, autoHideHour = false) {
  // 计算小时、分钟和秒数
  const hours = Math.floor(duration / 3600);
  const minutes = Math.floor((duration % 3600) / 60);
  const seconds = Math.floor(duration % 60);

  // 格式化时间字符串
  const formattedHours = String(hours).padStart(2, "0") + ":";
  const formattedMinutes = String(minutes).padStart(2, "0");
  const formattedSeconds = String(seconds).padStart(2, "0");
  if (autoHideHour && hours == 0) {
    return `${formattedMinutes}:${formattedSeconds}`;
  }

  // 返回格式化后的时间字符串
  return `${formattedHours}${formattedMinutes}:${formattedSeconds}`;
}

export function deepMerge(obj1, obj2) {
  for (let key in obj2) {
    obj1[key] =
      obj1[key] && obj1[key].toString() === "[object Object]"
        ? deepMerge(obj1[key], obj2[key])
        : (obj1[key] = obj2[key]);
  }
  return obj1;
}

export function require_factory(cols) {
  let res = {};
  for (let col of cols) {
    res[col] = {
      required: true,
      message: "请输入",
      trigger: "blur"
    };
  }
  return res;
}

export const formatFileSize = bytes => {
  if (bytes < 1024) {
    return bytes + " B";
  } else if (bytes < 1048576) {
    return (bytes / 1024).toFixed(2) + " KB";
  } else if (bytes < 1073741824) {
    return (bytes / 1048576).toFixed(2) + " MB";
  } else {
    return (bytes / 1073741824).toFixed(2) + " GB";
  }
};

export function difference(arr1, arr2) {
  return arr1.filter(x => !arr2.includes(x));
}

export function getSpanArr(listRow, columns = [], key_column = "") {
  if (columns.length == 0) {
    return listRow;
  }

  let list = [...listRow];
  list.forEach(item => {
    for (let col of columns) {
      item[`rowspan_${col}`] = 1;
    }
  });
  for (let col of columns) {
    for (let i = 0; i < list.length; i++) {
      let hasSpan = false;
      for (let j = i + 1; j < list.length; j++) {
        if (
          list[i][col] == list[j][col] &&
          (!key_column ||
            (key_column && list[i][key_column] == list[j][key_column]))
        ) {
          list[i][`rowspan_${col}`]++;
          list[j][`rowspan_${col}`]--;
          hasSpan = true;
        }
      }
      if (hasSpan) {
        i = i + list[i][`rowspan_${col}`] - 1;
      }
    }
  }
  return list;
}

export function extractDeptIdNames(data, parentName = "") {
  let result = {};

  for (let item of data) {
    let fullName = parentName ? `${parentName}>${item.name}` : item.name;
    // result[item.id] = fullName.replace("云学堂信息科技（江苏）有限公司", '')
    if (item.children && item.children.length > 0) {
      let childrenData = extractDeptIdNames(item.children, fullName);
      result = { ...result, ...childrenData };
    }
  }

  return result;
}

export const getOssUrl = id => {
  if (checkInElectron()) {
    return `assets/${id}`;
  }
  return `${import.meta.env.VITE_IMAGE_OSS_PATH}${id}`;
};

export const getAssetUrl = id => {
  return `assets/${id}`;
};

export function differenceObj(arr1, arr2, id = "id") {
  const uids = new Set(arr2.map(item => item[id]));
  return arr1.filter(item => !uids.has(item[id]));
}

export function union(arr1, arr2) {
  return [...arr1, ...differenceObj(arr2, arr1)];
}

export function randomId() {
  return Math.random().toString(16).slice(2);
}

export function getSalesTagsConverted(data) {
  return {
    customer: data["customerTopics"].map(x => x.label),
    internal: data["internalTopics"].map(x => x.label),
    categories: data.categories.map(x => x.name),
    data: data
  };
}

export const calcCategoryIdNameMap = list => {
  const data = {};
  for (let i = 0; i < list.length; i++) {
    const x = list[i];
    data[x.categoryId] = x.categoryName;
  }
  return data;
};

export const getCompanyLogoUrl = url => {
  if (url && url.startsWith("http")) {
    return url;
  }
  return getOssUrl("customer_logo.png");
};

// 模拟path.join 写一个把字符串拼接成路径的方法
export const pathJoin = (...paths) => {
  return paths.join("/").replace(/\\/g, "/");
};

export const isMac = () => {
  return navigator.userAgent.indexOf("Macintosh") > -1;
};

export const checkInElectron = () => {
  const userAgent = navigator.userAgent;
  const testElectron = /(Electron)/i.test(userAgent);
  const testFeishu = /(appCenter SuperApp)/i.test(userAgent);
  return testElectron && !testFeishu;
};

export const getClientType = () => {
  if (checkInElectron()) {
    if (isMac()) {
      return "mac";
    } else {
      return "win";
    }
  } else {
    if (isPC()) {
      return "web";
    } else {
      return "mobile";
    }
  }
};

export const getDay06 = date => {
  const currDate = new Date(date);
  const startOfWeek = new Date(currDate);
  startOfWeek.setDate(currDate.getDate() - currDate.getDay()); // 设置为周日

  const endOfWeek = new Date(currDate);
  endOfWeek.setDate(currDate.getDate() + (6 - currDate.getDay())); // 修正：直接用当前日期计算到周六的偏移
  return [startOfWeek, endOfWeek];
};

const getPlanStatusType = plan => {
  const now = new Date();
  const startTime = plan["scheduleStartTime"] || plan["startTime"];
  const endTime = plan["scheduleEndTime"] || plan["endTime"];
  const startTimeDt = new Date(startTime);
  const endTimeDt = new Date(endTime);
  const fifteenMinsBefore = new Date(startTimeDt.getTime() - 15 * 60 * 1000);

  if (plan.inProgress) {
    return "ongoing";
  } else {
    // 检查是否在待开始时间区间内且没有录制记录
    if (now >= fifteenMinsBefore && now <= endTimeDt && !plan.conferenceId) {
      return "notStarted";
    } else {
      return "";
    }
  }
};

// 添加日期分组函数
export function groupPlansByDate(plans) {
  let grouped = {};
  let _plans = [...plans];
  _plans.forEach(plan => {
    const startTime = plan["scheduleStartTime"] || plan["startTime"];
    const endTime = plan["scheduleEndTime"] || plan["endTime"];
    const date = startTime.substring(0, 10);
    if (!grouped[date]) {
      grouped[date] = [];
    }
    plan["startDt"] = startTime.substring(11, 16);
    plan["endDt"] = endTime.substring(11, 16);
    //添加一个字段，表示是否是过期的沟通，昨天之前的沟通都算过期
    plan["isExpired"] = endTime < now("yyyy-MM-dd");
    plan["status"] = getPlanStatusType(plan);
    // 如果开始时间和结束日期不在同一天，inSameDay设置为false
    plan["inSameDay"] = startTime.substring(0, 10) == endTime.substring(0, 10);
    grouped[date].push(plan);
  });
  // 按日期排序
  grouped = Object.keys(grouped)
    .sort()
    .reduce((obj, key) => {
      // 按startTime从小到大排序
      obj[key] = grouped[key].sort((a, b) =>
        a.scheduleStartTime.localeCompare(b.scheduleStartTime)
      );
      return obj;
    }, {});
  return grouped;
}

export const updatePlanApiParam = param => {
  // 创建一个表示本地时间的 Date 对象
  const startDt = new Date(`${param.startDate}T${param.startTime}`);

  // 计算结束时间（本地时间）
  const endDt = new Date(startDt.getTime() + param.duration * 60 * 1000);

  // 格化日期和时间
  param.endDate = formatDate(endDt, "yyyy-MM-dd");
  param.endTime = formatDate(endDt, "hh:mm");
  param.startWeek = "周" + formatDate(param.startDate, "w");

  return param;
};

export const mergeColumnsAndData = (titles, cateIdNameMap, raw) => {
  const mergedArray = [];
  for (let i = 0; i < raw.length; i++) {
    const data = raw[i].details;
    const obj = {};
    for (let j = 0; j < titles.length; j++) {
      obj[titles[j]] = data[j];
    }
    obj["id"] = raw[i].id;
    obj["categoryId"] = raw[i].categoryId;
    obj["listId"] = raw[i].listId;
    obj["_label"] = data[0];
    obj["所属分类"] = cateIdNameMap[raw[i].categoryId];
    mergedArray.push(obj);
  }
  return mergedArray;
};

export const toClipboard = async text => {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch (err) {
    // 如果navigator.clipboard不可用，使用传统方法
    try {
      const textarea = document.createElement("textarea");
      textarea.value = text;
      textarea.style.position = "fixed";
      textarea.style.opacity = "0";
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand("copy");
      document.body.removeChild(textarea);
      return true;
    } catch (e) {
      console.error("复制失败:", e);
      return false;
    }
  }
};

export const trimObject = data => {
  Object.keys(data).forEach(key => {
    if (typeof data[key] === "string") {
      data[key] = data[key].trim();
    }
  });
  return data;
};

export const getDateByTimeUnit = unit => {
  const date = new Date();
  const localDate = new Date(date.getTime() + date.getTimezoneOffset() * 60000);
  const year = localDate.getFullYear();
  const month = localDate.getMonth();
  const quarter = Math.floor(month / 3);
  const day = localDate.getDay(); // 获取星期几 (0-6, 0代表周日)
  let startDate = null;
  let endDate = null;
  const adaytime = 24 * 60 * 60 * 1000;
  switch (unit) {
    case "week":
      startDate = new Date(localDate.getTime() - day * 24 * 60 * 60 * 1000); // 本周日
      endDate = new Date(localDate.getTime() + (6 - day) * 24 * 60 * 60 * 1000); // 本周六
      break;
    case "month":
      startDate = new Date(Date.UTC(year, month, 1)); // 本月第一天
      endDate = new Date(Date.UTC(year, month + 1, 0)); // 本月最后一天
      break;
    case "quarter":
      startDate = new Date(Date.UTC(year, quarter * 3, 1)); // 本季度第一天
      endDate = new Date(Date.UTC(year, (quarter + 1) * 3, 0)); // 本季度最后一天
      break;
    case "year":
      startDate = new Date(Date.UTC(year, 0, 1)); // 本年1月1日
      endDate = new Date(Date.UTC(year, 11, 31)); // 本年12月31日
      break;
    case "last_week":
      startDate = new Date(localDate.getTime() - 7 * adaytime); // 7天前
      endDate = localDate; // 返回今天
      break;
    case "last_month":
      startDate = new Date(localDate.getTime() - 30 * adaytime); // 30天前
      endDate = localDate; // 返回今天
      break;
    case "last_quarter":
      startDate = new Date(localDate.getTime() - 90 * adaytime); // 90天前
      endDate = localDate; // 返回今天
      break;
    case "last_year":
      startDate = new Date(localDate.getTime() - 365 * adaytime); // 365天前
      endDate = localDate; // 返回今天
      break;
    default:
      startDate = date;
      endDate = date;
  }
  // console.log('startDate', unit, startDate, endDate)
  return {
    startDate,
    endDate
  };
};

export const getDateRangeStr = (type = "quarter") => {
  const { startDate, endDate } = getDateByTimeUnit(type);
  return {
    startDt: formatDate(startDate, "yyyy-MM-dd") + " 00:00:00",
    endDt: formatDate(endDate, "yyyy-MM-dd") + " 23:59:59"
  };
};

export const generateUrl = (baseUrl, params) => {
  const queryString = Object.entries(params)
    .filter(([_, value]) => value !== undefined && value !== null)
    .map(
      ([key, value]) =>
        `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
    )
    .join("&");

  return queryString ? `${baseUrl}?${queryString}` : baseUrl;
};

export const getSecondsShowTime = recordDurationSeconds => {
  if (!recordDurationSeconds) {
    return "-";
  }
  const hour = Math.floor(recordDurationSeconds / 3600);
  let min = Math.floor((recordDurationSeconds % 3600) / 60);
  let txt = "";
  if (hour > 0) {
    txt += `${hour}小时`;
  }
  if (min > 0 || hour === 0) {
    if (hour == 0 && min == 0) {
      min = 1;
    }
    txt += `${min}分钟`;
  }
  return txt;
};

// 将秒数转换为时分秒格式
export const secondsToTime = seconds => {
  if (!seconds) return "00:00:00";

  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);

  return [hours, minutes, secs]
    .map(v => v.toString().padStart(2, "0"))
    .join(":");
};

export const isJson = data => {
  try {
    JSON.parse(data);
    return true;
  } catch (e) {
    return false;
  }
};

export const findIndexOfStr = function (searchChar, str) {
  let regex = new RegExp(searchChar, "g");
  let indexArray = [];
  let match;
  while ((match = regex.exec(str)) !== null) {
    indexArray.push(match.index);
  }
  return indexArray;
};
